<template>
    <div>
        <el-page-header @back="goBack" :content="pageTitle"></el-page-header>
        <div class="common_line"></div>
        <el-form ref="addForm" :model="addForm" :rules="rules" label-width="90px" style="margin-top: 20px;width: 85%;">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="角色名称:" prop="name">
                        <el-input :disabled="isSystemRole" style="width: 240px" v-model="addForm.name" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="排序:">
                        <el-input :disabled="isSystemRole" style="width: 240px" v-model="addForm.sort" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="是否启用:">
                        <el-select :disabled="isSystemRole" style="width: 240px;" v-model="addForm.status" placeholder="请选择" clearable>
                            <el-option label="启用" :value="1"></el-option>
                            <el-option label="禁用" :value="0"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!roleId">
                    <el-form-item label="快捷选择:">
                        <el-select style="width: 240px;" v-model="defaultRoleName" placeholder="请选择" 
                            @change="defaultRoleChange" clearable>
                            <el-option v-for="(item, index) in defaultRoles" :key="'def_'+index" 
                                :label="item.name" :value="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item>
                        <span slot="label">
                            <i class="red_dot">*</i>
                            权限设置:</span>
                        <el-tabs tab-position="left">
                            <el-tab-pane v-for="item in permissions" :key="'perm'+item.index" :label="item.name">
                                <div class="top">
                                    <span>全选</span>
                                    <el-switch v-model="item.selectAll" active-color="#068CEE" @change="switchAllChange($event, item)"></el-switch>
                                </div>
                                <div class="permissions">
                                    <div class="item" v-for="_item in item.items" :key="'item_'+_item.id">
                                        <div>{{ _item.name }}</div>
                                        <el-switch v-model="_item.selected" active-color="#068CEE" @change="switchChange($event, _item)"></el-switch>
                                    </div>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </el-form-item>
                    <div v-if="!addForm.permissions.length" class="show_error">请设置权限</div>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="角色描述:">
                        <el-input :disabled="isSystemRole" maxlength="200" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" 
                            v-model="addForm.remark" placeholder="请输入" clearable />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <bottom-btns
            Width="70%"
            MarginTop="30px"
            :buttons="buttonList"
            @superBtnClick="handleButtonClick"
        ></bottom-btns>
    </div>
</template>

<script>
import bottomBtns from "@/components/bottomBtns";
import { getSystemRoleList, infoRole, addRole, editRole, listPromise } from '@/api/role';

export default {
    name: 'addRole',
    components: {
        bottomBtns
    },
    data() {
        return {
            isSystemRole: false,
            roleId: '',
            pageTitle: '',
            addForm: {
                corp: '',
                name: '',
                sort: '',
                status: 1,
                permissions: [],
                remark: ''
            },
            rules:{
                name: [
                    { required: true, message: "请输入客户名称", trigger: "blur" },
                ]
            },
            defaultRoleName: '',
            defaultRoles: [],
            defaultPermissions: [],
            permissions: [
					{name: '用户管理', items: [], index: 1, selectAll: false},
					{name: '角色管理', items: [], index: 2, selectAll: false},
					{name: '销售开单管理', items: [], index: 3, selectAll: false},
					{name: '销售退货管理', items: [], index: 4, selectAll: false},
					{name: '销售预订', items: [], index: 5, selectAll: false},
					{name: '采购管理', items: [], index: 6, selectAll: false},
					{name: '采购退货管理', items: [], index: 7, selectAll: false},
					{name: '采购预订', items: [], index: 8, selectAll: false},
					{name: '客户管理', items: [], index: 9, selectAll: false},
					{name: '供货商管理', items: [], index: 10, selectAll: false},
					{name: '商品管理', items: [], index: 11, selectAll: false},
					{name: '日常收支', items: [], index: 12, selectAll: false},
					{name: '组装拆分', items: [], index: 13, selectAll: false},
					{name: '待办管理', items: [], index: 14, selectAll: false},
					{name: '其他设置', items: [], index: 15, selectAll: false},
            ],
            buttonList: [
                { name: '保存', type: 'commit', id:'1' },
                { name: '取消', type: 'cancel', id:'2' }
            ]
        }
    },
    props: {
        corpId: {
            type: Number
        },
        editId: {
            type: Number
        }
    },
    mounted() {
        this.addForm.corp = this.corpId
        this.roleId = this.editId
        if (this.roleId) {
            this.pageTitle = '编辑角色'
        }else{
            this.pageTitle = '新增角色'
            this.getSystemRoles()
        }
        this.getPermissions()
    },
    methods: {
        goBack() {
            this.$emit('hidden', '')
        },
        // 详情
        getRoleInfo() {
            infoRole(this.roleId, {corp: this.addForm.corp}).then(res => {
                if (res.code == 200){
                    let infos = res.data.data
                    this.addForm.name = infos.name
                    this.addForm.sort = infos.sort
                    this.addForm.status = infos.status?1:0
                    this.addForm.remark = infos.remark
                    this.isSystemRole = infos.is_system
                    this.addForm.permissions = infos.permissions
                    if (infos.permissions && infos.permissions.length){
                        this.permissions.forEach(group => {
                            group.items.forEach(item => {
                                if (infos.permissions.includes(item.id)) {
                                    // 设置 selected 为 true
                                    item.selected = true;
                                }
                            })
                        })
                    }
                }
            })
        },
        // 获取系统预设的角色
        getSystemRoles() {
            getSystemRoleList({corp: this.addForm.corp}).then(res => {
                this.defaultRoles = res.data.data
            })
        },
        // 获取权限列表
        getPermissions() {
            let _this = this
            listPromise({corp: this.addForm.corp}).then(res => {
                let lists = res.data.data.permissions_list
                lists.forEach((item, index) => {
                    _this.permissions.forEach(_item => {
                        if (_item.name == item.remark){
                            item.selected = false
                            item.parentIndex = _item.index
                            _item.items.push(item)
                        }
                    })
                })
                if (_this.roleId){
                    _this.getRoleInfo()
                }
            })
        },
        handlePermissions() {
            let array = []
            this.permissions.forEach(group => {
                group.items.forEach(item => {
                    if (item.selected){
                        array.push(item.id)
                    }
                })
            })
            return array
        },
        defaultRoleChange(val) {
            // 先清除上一次赋值的权限
            if (this.defaultPermissions.length){
                this.permissions.forEach(group => {
                    group.items.forEach(item => {
                        if (this.defaultPermissions.includes(item.id)) {
                            // 设置 selected 为 false
                            item.selected = false;
                        }
                    })
                })
            }

            let info = {}
            this.defaultRoles.forEach(item =>{
                if (item.name == val) {
                    info = item
                }
            })
            let defaultPermissions = info.permissions
            this.defaultPermissions = defaultPermissions 
            if (defaultPermissions && defaultPermissions.length){
                this.permissions.forEach(group => {
                    group.items.forEach(item => {
                        if (defaultPermissions.includes(item.id)) {
                            // 设置 selected 为 true
                            item.selected = true;
                        }
                    })
                })
            }
            this.addForm.permissions = this.handlePermissions()
        },
        switchAllChange(val, item) {
            // 直接修改 item.items 中每个元素的 selected 属性
            item.items.forEach(elem => {
                elem.selected = val; // 设置当前状态为全选开关的值
            });
            this.addForm.permissions = this.handlePermissions()
        },
        switchChange(val, item) {
            // 找到当前项所属的权限组
            const permissionGroup = this.permissions.find(group => {
                return group.index === item.parentIndex;
            });

            // 检查该组中是否所有开关都被选中
            const allSelected = permissionGroup.items.every(elem => elem.selected);

            // 更新全选开关的状态
            permissionGroup.selectAll = allSelected;
            this.addForm.permissions = this.handlePermissions()
        },
        handleButtonClick(item) {
            switch (item.id) {
                case '1':   // 保存
                    this.commit()
                    break;
                case '2':   // 取消
                    this.goBack()
                    break;
            
                default:
                    break;
            }
        },
        commit() {
            var that = this
            that.$refs['addForm'].validate(valid => {
                if(!valid) return

                that.addForm.permissions = this.handlePermissions()
                if (!that.addForm.permissions.length) return

                let temp = null
                if (that.roleId) {
                    temp = editRole(that.roleId, that.addForm)
                }else{
                    temp = addRole(that.addForm)
                }
                temp.then(res => {
                    if (res.code == 200){
                        that.$message({
                            message: '操作成功',
                            type: 'success'
                        })
                        that.$emit('success')
                    }
                })
            })
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    .top {
        width: 80%;
        text-align: right;
        padding-left: 10px;
        padding-bottom: 10px;
        span {
            margin-right: 5px;
            color: @blue;
            font-weight: bold;
        }
    }
    .red_dot {
        color: #ff4949;
        margin-right: 4px;
    }
    .show_error {
        color: #F56C6C;
        font-size: 12px;
        line-height: 1;
        padding-bottom: 20px;
        margin-left: 100px;
    }
    .permissions {
        width: 80%;
        padding-left: 10px;
        .item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #eee;
            height: 44px;
            line-height: 44px;
        }
    }
</style>